/*
 * Copyright (c) 2016 . All Rights Reserved.
 */
package com.cgmnx.admin.service.sys.impl;

import com.aliyun.oss.ClientException;
import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;
import com.aliyun.oss.OSSException;
import com.aliyun.oss.model.PutObjectResult;
import com.cgmnx.admin.service.sys.FileUploadService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.io.ByteArrayInputStream;
import java.io.InputStream;

/**
 * @author: created  Date: 16/12/20 Time: 下午2:30
 * @version: 1.0
 */
@Slf4j
@Service
public class OssFileUploadService implements FileUploadService {

    @Value("${aliyun.oss.endpoint}")
    private String endpoint;
    @Value("${aliyun.oss.accessKeyId}")
    private String accessKeyId;
    @Value("${aliyun.oss.accessKeySecret}")
    private String accessKeySecret;
    @Value("${aliyun.oss.bucketName}")
    private String bucketName;

    private final static String HTTP = "http://";

    private final static String DOT = ".";

    private final static String SLASH = "/";

    private OSS createOssClient() {
        return new OSSClientBuilder().build(endpoint, accessKeyId, accessKeySecret);
    }

    /**
     * @param key   文件名
     * @param bytes
     * @return
     */
    @Override
    public String upload(String key, byte[] bytes) {
        OSS ossClient = createOssClient();
        try {

            PutObjectResult putObjectResult = ossClient.putObject(bucketName, key, new ByteArrayInputStream(bytes));

            if (putObjectResult == null) {
                return StringUtils.EMPTY;
            }
            return putObjectResult.getRequestId();
        } catch (OSSException oe) {
            log.error("Caught an OSSException, which means your param made it to OSS, "
                            + "but was rejected with an error response for some reason," +
                            "Error Code:{},Error Message,Request ID:{},Host ID:{}",
                    oe.getErrorCode(), oe.getMessage(), oe.getRequestId(), oe.getHostId());
            return StringUtils.EMPTY;
        } catch (ClientException ce) {
            log.error("Caught an ClientException, which means the client encountered "
                    + "a serious internal problem while trying to communicate with OSS, "
                    + "such as not being able to access the network.", ce);
            return null;
        } catch (Throwable throwable) {
            log.error("Caught an ClientException, which means the client encountered ", throwable.getMessage());
            return StringUtils.EMPTY;
        } finally {
            // 使用完就直接关闭
            ossClient.shutdown();
        }
    }

    @Override
    public String upload(String key, InputStream inputStream) {
        OSS ossClient = createOssClient();
        try {
            long startTime = System.currentTimeMillis();
            PutObjectResult putObjectResult = ossClient.putObject(bucketName, key, inputStream);
            log.info("上传文件到文件服务器执行时间:{}", System.currentTimeMillis() - startTime);
            if (putObjectResult == null) {
                return StringUtils.EMPTY;
            }
            return HTTP + bucketName + DOT + endpoint + SLASH + key;
        } catch (OSSException oe) {
            log.error("Caught an OSSException, which means your param made it to OSS, "
                            + "but was rejected with an error response for some reason," +
                            "Error Code:{},Error Message,Request ID:{},Host ID:{}",
                    oe.getErrorCode(), oe.getMessage(), oe.getRequestId(), oe.getHostId());
            return StringUtils.EMPTY;
        } catch (ClientException ce) {
            log.error("Caught an ClientException, which means the client encountered "
                    + "a serious internal problem while trying to communicate with OSS, "
                    + "such as not being able to access the network.", ce);
            return null;
        } catch (Throwable throwable) {
            log.error("Caught an ClientException, which means the client encountered ", throwable.getMessage());
            return StringUtils.EMPTY;
        } finally {
            // 使用完就直接关闭
            ossClient.shutdown();
        }
    }

    @Override
    public InputStream download(String location) {
        return null;
    }


}